import { App, Avatar, ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN'; // 切换为中文
import dayjs from 'dayjs';
import { NotificationView, TreadstoneProvider } from 'treadstone-components';

import { AvatarDropdown, AvatarName, Question, SelectLang } from '@/components';
import { history } from '@umijs/max';

import defaultSettings from '../config/defaultSettings';
import { TREADSTONE_APP_ID, TREADSTONE_SERVER_URL } from './common/constant';
import { StorageKey } from './common/enum';
import BasicLayout from './layouts/BasicLayout';
import { errorConfig } from './requestErrorConfig';
import { queryCurrentUser } from './services/user';

import 'dayjs/locale/zh-cn';

import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
const loginPath = new URL('/user/login', TREADSTONE_SERVER_URL);
dayjs.locale('zh-cn');
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const urlParams = new URLSearchParams(window.location.search);
  const token = urlParams.get('token');
  if (token) {
    localStorage.setItem(StorageKey.ACCESS_TOKEN, token);
    urlParams.delete('token');
    const newPath = window.location.pathname + '?' + urlParams.toString();
    history.replace(newPath);
  }
  const fetchUserInfo = async () => {
    try {
      const result = await queryCurrentUser({ appId: TREADSTONE_APP_ID });
      return result.data;
    } catch (error) {
      loginPath.searchParams.append('redirect', window.location.href);
      window.location.replace(loginPath.href);
    }
    return undefined;
  };
  const currentUser = await fetchUserInfo();
  return {
    fetchUserInfo,
    currentUser,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    actionsRender: () => [
      <Question key="doc" />,
      <SelectLang key="SelectLang" />,
      <NotificationView key={'notification'} />,
    ],
    logo: <Avatar src="/logo.png" shape="circle" style={{ borderRadius: 6 }} />,
    avatarProps: {
      shape: 'circle',
      title: <AvatarName />,
      style: { borderRadius: 6 },
      alt: initialState?.currentUser?.name,
      src: initialState?.currentUser?.avatar,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => null,
    onPageChange: () => {
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser) {
        loginPath.searchParams.append('redirect', window.location.href);
        window.location.replace(loginPath.href);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: [],
    menuHeaderRender: undefined,
    menu: {
      hideMenuWhenCollapsed: true,
      // request: async (_, menus) => {
      //   if (initialState?.currentUser) {
      //     return menus
      //       .filter(
      //         (item) =>
      //           initialState.currentUser?.resources?.some((resource) => resource.uuid === item.uuid) ||
      //           ['/', '*', '/welcome'].includes(item.path!),
      //       )
      //       .map((item) => ({
      //         ...item,
      //         children: item.children?.filter((route: MenuDataItem) =>
      //           initialState.currentUser?.resources?.some((resource) => resource.uuid === route.uuid),
      //         ),
      //         routes: item.routes?.filter((route: MenuDataItem) =>
      //           initialState.currentUser?.resources?.some((resource) => resource.uuid === route.uuid),
      //         ),
      //       }));
      //   }
      //   return [];
      // },
    },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return <BasicLayout>{children}</BasicLayout>;
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};

export function rootContainer(container: React.ReactNode) {
  return (
    <ConfigProvider locale={zhCN}>
      <TreadstoneProvider appId={TREADSTONE_APP_ID} server={{ treadstone: TREADSTONE_SERVER_URL }}>
        <App>{container}</App>
      </TreadstoneProvider>
    </ConfigProvider>
  );
}
